package socket

import (
	"titargo/models"
	"github.com/gin-gonic/gin/json"
)

// 客户端组
type Hub struct {
	clients map[*Client]bool

	broadcast chan []byte

	register chan *Client

	unregister chan *Client
}

func NewHub() *Hub {
	return &Hub{
		broadcast:  make(chan []byte),
		register:   make(chan *Client),
		unregister: make(chan *Client),
		clients:    make(map[*Client]bool),
	}
}

func (h *Hub) Run() {
	for {
		select {
		case client := <-h.register:
			h.clients[client] = true
			var send_data = &SendData{Users:h.GetUsers(),MsgType:msg_type_userlist}
			send_data.CheckTime()
			var users_json,_ = json.Marshal(send_data)
			h.SendAllUser(users_json)
		case client := <-h.unregister:
			if _, ok := h.clients[client]; ok {
				delete(h.clients, client)
				close(client.send)
			}
			var send_data = &SendData{Users:h.GetUsers(),MsgType:msg_type_userlist}
			send_data.CheckTime()
			var users_json,_ = json.Marshal(send_data)
			h.SendAllUser(users_json)
		case message := <-h.broadcast:
			for client := range h.clients {
				select {
				case client.send <- message:
				default:
					close(client.send)
					delete(h.clients, client)
				}
			}
		}
	}
}

func(h *Hub) GetUsers() []*models.User{
	var users []*models.User
	for client := range h.clients {
		users = append(users,client.user)
	}
	return users
}

func(h *Hub) SendAllUser(message []byte){
	for client := range h.clients {
		select {
		case client.send <- message:
		default:
			close(client.send)
			delete(h.clients, client)
		}
	}
}

func(h *Hub) Broadcast(message [] byte){
	for client := range h.clients{
		select{
		case client.send<-message:
		default:
			close(client.send)
			delete(h.clients,client)
		}
	}
}
